package com.qf.service.impl;

import com.qf.bo.RoleBO;
import com.qf.bo.UserBO;
import com.qf.dao.PermissionDao;
import com.qf.service.PermissionService;
import com.qf.util.SecurityUtils;
import com.qf.vo.PermissionVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 权限实现类
 *
 * @USER: Administrator
 * @DATE: 2025/9/6 下午2:03
 * @VERSION: 1.0.0
 */
@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionDao permissionDao;


    @Override
    public List<PermissionVO> queryCurUserPermission() {
        UserBO userBO = SecurityUtils.getCurrentUser().getUserBO();

        // 获取当前用户的所有角色id
        List<Long> roleIds = new ArrayList<>();
        for (RoleBO roleBO : userBO.getRoles()) {
            roleIds.add(roleBO.getId());
        }

        // 根据角色id查询权限
        List<PermissionVO> permissionVOS = permissionDao.queryCurUserPermission(roleIds);

        // 组装成树形结构
        return buildPermissionTree(permissionVOS, 0);
    }

    /**
     * 递归组装权限树形结构
     * @param allPermissions 所有权限集合
     * @param parentId 父级权限ID（初始为0，查询顶级权限）
     */
    private List<PermissionVO> buildPermissionTree(List<PermissionVO> allPermissions, Integer parentId) {
        List<PermissionVO> tree = new ArrayList<>();

        for (PermissionVO permission : allPermissions) {
            // 找到当前父级ID对应的子权限
            if (parentId.equals(permission.getParentId())) {
                // 递归查询当前权限的子权限，并设置到children字段
                List<PermissionVO> children = buildPermissionTree(allPermissions, permission.getId());
                permission.setChildren(children);

                // 添加到当前层级的集合中
                tree.add(permission);
            }
        }

        return tree;
    }

}
